<template>
  <div class="inventory-summary">
    <el-row :gutter="20">
      <el-col :span="9">
        <el-card class="summary-card">
          <div slot="header" class="card-header">
            <span>今日概况</span>
          </div>
          <div class="inventory-button">
            <span class="stock-in-button">入库</span>
          </div>
          <div class="outentory-button">
            <span class="stock-in-button">出库</span>
          </div>
          <el-row>
            <el-col :span="10">
              <div><i class="el-icon-document"></i> <span class="highlight">单据数量:</span> {{ todayData.inboundCount }}</div>
            </el-col>
            <el-col :span="10">
              <div><i class="el-icon-document"></i> <span class="highlight">单据数量:</span> {{ todayData.outboundCount }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <div><i class="el-icon-goods"></i> <span class="highlight">入库数量:</span> {{todayData.quantityReceived }}</div>
            </el-col>
            <el-col :span="10">
              <div><i class="el-icon-truck"></i> <span class="highlight">出库数量:</span> {{ todayData.outStorage }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <div><i class="el-icon-money"></i> <span class="highlight">入库金额:</span> ¥{{ todayData.inboundPrice }}元</div>
            </el-col>
            <el-col :span="10">
              <div><i class="el-icon-sold-out"></i> <span class="highlight">出库金额:</span> ¥{{ todayData.unitPrice }}元</div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="9">
        <el-card class="summary-card">
          <div slot="header" class="card-header">
            <span>昨日概况</span>
          </div>
          <div class="inventory-button">
            <span class="stock-in-button">入库</span>
          </div>
          <div class="outentory-button">
            <span class="stock-in-button">出库</span>
          </div>
          <el-row>
            <el-col :span="10">
              <div><i class="el-icon-document"></i> <span class="highlight">单据数量:</span> {{ yesterdayData.inboundCount }}</div>
            </el-col>
            <el-col :span="10">
              <div><i class="el-icon-document"></i> <span class="highlight">单据数量:</span> {{ yesterdayData.outboundCount }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <div><i class="el-icon-goods"></i> <span class="highlight">入库数量:</span> {{ yesterdayData.quantityReceived }}</div>
            </el-col>
            <el-col :span="10">
              <div><i class="el-icon-truck"></i> <span class="highlight">出库数量:</span> {{ yesterdayData.outStorage }}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <div><i class="el-icon-money"></i> <span class="highlight">入库金额:</span> ¥{{ yesterdayData.inboundPrice }}元</div>
            </el-col>
            <el-col :span="10">
              <div><i class="el-icon-sold-out"></i> <span class="highlight">出库金额:</span> ¥{{ yesterdayData.unitPrice }}元</div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <!--饼图-->
    <el-row :gutter="20">
      <el-col :span="9">
        <el-card class="summary-card">
          <div slot="header" class="card-header">
            <span>库存数量占比</span>
          </div>
          <div class="echart-container" ref="inventoryChart"></div>
        </el-card>
      </el-col>

      <el-col :span="9">
        <el-card id="money-card" class="summary-card">
          <div slot="header" class="card-header">
            <span>库存金额占比</span>
          </div>
          <div class="echart-container" ref="moneyChart"></div>
        </el-card>
      </el-col>
    </el-row>

<!-- 待办事项 -->
     <el-card class="task-card">
    <div slot="header" class="clearfix">
      <span>代办事项</span>
    </div>
    <span class="sx">待审核</span>
    <el-row :gutter="20">
      <el-col :span="8" v-for="(item, index) in toExamineList" :key="index">
        <el-card>
          <div>{{ item.name }}</div>
          <div>{{ item.count }}</div>
        </el-card>
      </el-col>
    </el-row>
    <el-divider></el-divider>
    <span class="sx">待执行</span>
    <el-row :gutter="20">
      <el-col :span="8" v-for="(item, index) in executeList" :key="index">
        <el-card>
          <div>{{ item.name }}</div>
          <div>{{ item.count }}</div>
        </el-card>
      </el-col>
    </el-row>
  </el-card>

  <!-- 入库统计 -->
  <div class="inventory-stats">
    <el-card>
      <div slot="header" class="store">
        <span>入库统计</span>
      </div>
      <el-radio-group v-model="selectedInDateRange" class="storeClass">
        <el-radio-button label="最近7天">最近7天</el-radio-button>
        <!-- <el-radio-button label="最近30天">最近30天</el-radio-button>
        <el-radio-button label="最近一年">最近一年</el-radio-button> -->
      </el-radio-group>
      <div ref="storeChart" class="chart"></div>
    </el-card>
  </div>

  <!-- 出库统计 -->
  <div class="inventory-stats">
    <el-card>
      <div slot="header" class="store">
        <span>出库统计</span>
      </div>
      <el-radio-group v-model="selectedOutDateRange" class="storeClass">
        <el-radio-button label="最近7天">最近7天</el-radio-button>
        <!-- <el-radio-button label="最近30天">最近30天</el-radio-button>
        <el-radio-button label="最近一年">最近一年</el-radio-button> -->
      </el-radio-group>
      <div ref="outboundChart" class="chart"></div>
    </el-card>
  </div>

<!-- 预警信息 -->
   <el-card class="warning-card">
    <div slot="header" class="store">
      <span>预警信息</span>
    </div>
    <el-row :gutter="20">
      <el-col :span="12" v-for="(warning, index) in warnings" :key="index">
        <el-card>
          <div class="warning-icon" ></div>
          <div>{{ warning.message }}</div>
          <div class="warning-count" >{{ warning.count }}</div>
        </el-card>
      </el-col>
    </el-row>
  </el-card>

<!-- 系统消息 -->
  <el-card class="messages-card">
    <div slot="header" class="store">
      <span>系统消息</span>
      <el-button style="float: right;" type="text" @click="moreMessages">更多</el-button>
    </div>
    <el-timeline>
      <el-timeline-item
        v-for="(message, index) in messageList"
        :key="index"
        :timestamp="message.time"
        type="primary"
      >
        {{ message.content }}
      </el-timeline-item>
    </el-timeline>
  </el-card>

    <!-- 入库排名 -->
    <el-card class="ranking-card">
      <div slot="header" class="store">
        <span>入库排名</span>
      </div>
      <el-table :data="inboundData" style="width: 100%" max-height="300">
        <el-table-column label="排名" align="center" type="index" :index="indexMethod"></el-table-column>
        <el-table-column prop="productName" label="货品名称" width="170"></el-table-column>
        <el-table-column prop="quantityReceived" label="数量" width="170"></el-table-column>
        <el-table-column prop="inboundPrice" label="金额" width="170"></el-table-column>
        <el-table-column prop="nameCount" label="入库次数" width="170"></el-table-column>
      </el-table>
    </el-card>

    <!-- 出库排名 -->
    <el-card class="ranking-card-ck">
      <div slot="header" class="store">
        <span>出库排名</span>
      </div>
      <el-table :data="outboundData" style="width: 100%" max-height="400">
        <el-table-column label="排名" align="center" type="index" :index="indexMethod"></el-table-column>
        <el-table-column prop="productName" label="货品名称" width="170"></el-table-column>
        <el-table-column prop="outStorage" label="数量" width="170"></el-table-column>
        <el-table-column prop="unitPrice" label="金额" width="170"></el-table-column>
        <el-table-column prop="nameCount" label="出库次数" width="170"></el-table-column>
      </el-table>
    </el-card>


  </div>
</template>

<script>
import * as echarts from 'echarts';
import { selectBsWarehouseQuantity,selectBsWarehouseMoney } from '@/api/warehouse/warehouse'// 库存
import { selectPyInboundStatistics, selectPyInboundRanking } from '@/api/inbound/inbound' // 入库
import { selectWhOutboundStatistics,selectWhOutboundRanking } from '@/api/outbound/outbound' //出库
import { selectOverview } from '@/api/outbound/outbound'// 概况
import { selectToExamine, selectExecute } from '@/api/outbound/outbound' //待办事项
import { selectMessage }from '@/api/message/message' //系统消息
import {selectInventoryDetails}from '@/api/ledger/details'//预警信息


export default {
  name: 'PieChartComponent',
  data() {
    return {
      // 今日概况
      todayData: {
        inboundCount: 0,
        quantityReceived: 0,
        inboundPrice: 0,
        outboundCount: 0,
        unitPrice: 0,
        outStorage: 0,
      },
      //昨日概况
      yesterdayData: {
        inboundCount: 0,
        quantityReceived: 0,
        inboundPrice: 0,
        outboundCount: 0,
        unitPrice: 0,
        outStorage: 0,
      },
      //待办事项
      toExamineList: [],
      executeList: [],
      selectedInDateRange: '最近7天',
      selectedOutDateRange: '最近7天',
      chart: null,
      // 预警信息
       warnings: [
        { message: '库存高于上限', count: '4' },
        // { message: '库存低于上限', count: '2', iconClass: 'icon-low' },
        // { message: '临期货品', count: '1', iconClass: 'icon-expiry' },
        // { message: '到期货品', count: '5', iconClass: 'icon-due' }
      ],
      // 系统消息
      messageList: [],
      // 入库排名
      inboundData: [
        { rank: 1, productName: '货品一', quantityReceived: 50, inboundPrice: 200.00, nameCount: 6 },
      ],
      //出库排名
      outboundData: [
        { rank: 1, productName: '货品一', quantityReceived: 50, inboundPrice: 200.00, nameCount: 6 },
      ],
      // 库存数量占比
      inventoryData: [],
      // 库存金额占比
      moneyData: [],
    };
  },
  mounted() {
    //库存数量占比
    this.inventoryInitChart();
    //库存金额占比
    this.moneyInitChart();
    //入库统计
    this.storeInitChart();
    //出库统计
    this.outboundInitChart();
    //入库排名
    this.getInboundRanking();
    //出库排名
    this.getOutboundRanking();
    //今日概况
    this.getToDayOverview();
    //昨日概况
    this.getYesterDayOverview();
    //代办事项（待审核）
    this.getToExamine();
    //代办事项（待执行）
    this.getExecute();
    //系统消息
    this.getMessage();
    //预警信息
    this.getWarning();
  },
  methods: {
    // 预警信息
    getWarning(){
      selectInventoryDetails().then(response => {
        response.forEach(item => {
          if (item.message == '库存低于下限') {
            this.message = item.message;
            this.count = item.count;
          }else if (item.message == '库存高于上限') {
            this.message = item.message;
            this.count = item.count;
          }
        })
        this.warnings = response;
        console.log(response)
      })
    },
    //系统消息
    getMessage(){
      selectMessage().then(response => {
        this.messageList = response;
      })
    },

    //代办事项（待审核）
    getToExamine(){
      selectToExamine().then(response=>{
        this.toExamineList = response;
      })
    },
     //代办事项（待执行）
    getExecute(){
      selectExecute().then(response=>{
        this.executeList = response;
      })
    },
    //今日概况
    getToDayOverview() {
      // 获取当前日期
      const today = new Date();

      // 将日期格式化为 "yyyy-MM-dd" 格式
      function formatDate(date) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
      }

      const time = {
          time: formatDate(today)
      };

      console.log(time);
      selectOverview(time) .then(data => {
      // 处理返回的数据
      data.forEach(item => {
        if (item.inbound=='入库') {
          this.todayData.inboundCount = item.inboundCount;
          this.todayData.inboundPrice = item.inboundPrice;
          this.todayData.quantityReceived = item.quantityReceived;
        } else if (item.inbound=='出库') {
          this.todayData.outboundCount = item.inboundCount;
          this.todayData.unitPrice = item.inboundPrice;
          this.todayData.outStorage = item.quantityReceived;
          }
        });
      })
    },
    //昨日概况
    getYesterDayOverview() {
      // 获取当前日期
      const today = new Date();

      // 计算昨天的时间
      const pastDate = new Date(today);
      pastDate.setDate(today.getDate() - 1);

      // 将日期格式化为 "yyyy-MM-dd" 格式
      function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }

      const time = {
        time: formatDate(pastDate),
      };

      console.log(time);
      selectOverview(time).then(data => {
        // 处理返回的数据
        data.forEach(item => {
          if (item.inbound=='入库') {
          this.yesterdayData.inboundCount = item.inboundCount;
          this.yesterdayData.inboundPrice = item.inboundPrice;
          this.yesterdayData.quantityReceived = item.quantityReceived;
        } else if (item.inbound=='出库') {
          this.yesterdayData.outboundCount = item.inboundCount;
          this.yesterdayData.unitPrice = item.inboundPrice;
          this.yesterdayData.outStorage = item.quantityReceived;
          }
        });
      })
    },

    // 排名序号
    indexMethod(index) {
      return index + 1; // 从1开始计数
    },
    //入库排名
    getInboundRanking(){
      selectPyInboundRanking().then(response => {
        this.inboundData = response;
      });
    },
    //出库排名
    getOutboundRanking(){
      selectWhOutboundRanking().then(response => {
        this.outboundData = response;
      });
    },
    //库存数量占比
    inventoryInitChart() {
    selectBsWarehouseQuantity().then(response => {
      this.inventoryData = response;

      // 动态设置图表数据
      const chartData = this.inventoryData.bsWarehouses.map(warehouse => ({
        value: warehouse.currentInventory,
        name: warehouse.warehouseName,
        itemStyle: { color: this.getRandomColor() } // 可以根据需要生成随机颜色或其他逻辑
      }));

      const chartDom = this.$refs.inventoryChart;
      const myChart = echarts.init(chartDom);
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          itemGap: 20,
          itemWidth: 20,
          itemHeight: 14,
          orient: 'vertical',
          right: '0%',
          top: 'center',
          textStyle: {
            color: '#666'
          }
        },
        series: [
          {
            name: '库存',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}: {c}'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 15,
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: chartData // 使用从后端获取的数据
          }
        ],
        graphic: {
          type: 'text',
          left: 'center',
          top: 'center',
          style: {
            text: `${this.inventoryData.totalVessel}\n总库存`,
            textAlign: 'center',
            fill: '#000',
            fontSize: 20
          }
        }
      };
      myChart.setOption(option);
      console.log(chartData)
    });

    },
    getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
      return color;
    },

    //库存金额占比
    moneyInitChart() {
      selectBsWarehouseMoney().then(response => {
        this.moneyData = response;

         // 动态设置图表数据
        const chartData = this.moneyData.bsWarehouses.map(warehouse => ({
          value: `${ warehouse.inventoryValue }`,
          name: warehouse.warehouseName,
          itemStyle: { color: this.getRandomColor() } // 可以根据需要生成随机颜色或其他逻辑
        }));

        const chartDom = this.$refs.moneyChart;
        const myChart = echarts.init(chartDom);
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            itemGap: 20,
            itemWidth: 20,
            itemHeight: 14,
            orient: 'vertical',
            right: '0%',
            top: 'center',
            textStyle: {
              color: '#666'
            }
          },
          series: [
            {
              name: '金额',
              type: 'pie',
              radius: ['50%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: true,
                position: 'outside',
                formatter: '{b}: {c}'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 15,
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: true
              },
              data:chartData // 使用从后端获取的数据
            }
          ],
          graphic: {
            type: 'text',
            left: 'center',
            top: 'center',
            style: {
              text: `${this.moneyData.moneyVessel}.00\n总金额`,
              textAlign: 'center',
              fill: '#000',
              fontSize: 20
            }
          }
        };
        myChart.setOption(option);
        console.log(chartData)
      });
    },
    // 入库统计
    storeInitChart() {
      // 获取当前日期
      const today = new Date();

      // 计算前七天的日期
      const pastDate = new Date(today);
      pastDate.setDate(today.getDate() - 6);

      // 将日期格式化为 "yyyy-MM-dd" 格式
      function formatDate(date) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
      }

      const dateBeginEnd = {
          begin: formatDate(pastDate),
          end: formatDate(today)
      };

      console.log(dateBeginEnd);

      selectPyInboundStatistics(dateBeginEnd).then(response => {
        const chartDom = this.$refs.storeChart;
        const myChart = echarts.init(chartDom);
       // 提取后台返回的数据
      const data = response;

      // 提取日期、数量和金额
      const dates =data.dateList;
      const quantities =data.quantity;
      const amounts =data. price;

      const option = {
        tooltip: {},
        legend: {
          data: ['数量', '金额']
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: [
          {
            type: 'value',
            name: '数量',
            min: 0,
            max: Math.max(...quantities) + 100, // 动态设置最大值
            position: 'left'
          },
          {
            type: 'value',
            name: '金额',
            min: 0,
            max: Math.max(...amounts) + 1000, // 动态设置最大值
            position: 'right'
          }
        ],
        series: [
          {
            name: '数量',
            type: 'bar',
            data: quantities
          },
          {
            name: '金额',
            type: 'line',
            yAxisIndex: 1,
            data: amounts
          }
        ]
      };

        myChart.setOption(option);
      });

    },
     // 出库统计
    outboundInitChart() {
      // 获取当前日期
      const today = new Date();

      // 计算前七天的日期
      const pastDate = new Date(today);
      pastDate.setDate(today.getDate() - 6);

      // 将日期格式化为 "yyyy-MM-dd" 格式
      function formatDate(date) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
      }

      const dateBeginEnd = {
          begin: formatDate(pastDate),
          end: formatDate(today)
      };


        selectWhOutboundStatistics(dateBeginEnd).then(response => {

        const chartDom = this.$refs.outboundChart;
        const myChart = echarts.init(chartDom);

        // 提取后台返回的数据
        const data = response;

        // 提取日期、数量和金额
        const dates = data.dateList;
        const quantities = data.quantity;
        const amounts = data.price;


        const option = {
          tooltip: {},
          legend: {
            data: ['数量', '金额']
          },
          xAxis: {
            type: 'category',
            data: dates,
          },
          yAxis: [
            {
              type: 'value',
              name: '数量',
              min: 0,
              max: Math.max(...quantities) + 100, // 动态设置最大值
              position: 'left'
            },
            {
              type: 'value',
              name: '金额',
              min: 0,
              max: Math.max(...amounts) + 1000, // 动态设置最大值
              position: 'right'
            }
          ],
          series: [
            {
              name: '数量',
              type: 'bar',
              data: quantities,
              itemStyle: { // 柱状颜色和圆角
                color: '#f2bf24',
              },
            },
            {
              name: '金额',
              type: 'line',
              yAxisIndex: 1,
              data: amounts
            }
          ]
        };
        myChart.setOption(option);
      })
    },

    // 系统消息
    moreMessages() {
      // 跳转到更多消息的页面或显示更多消息的弹窗
      this.$router.push('/message');
      console.log('显示更多消息');
    }
  },
};
</script>

<style>
.inventory-summary {
  padding: 20px;
}
.summary-card {
  margin-bottom: 20px;
}
.card-header {
  font-weight: bold;
  background-color: #f5f7fa;
  padding: 10px;
  border-bottom: 1px solid #dcdfe6;
}
.highlight {
  color: darkgray;
  font-weight: bold;
  margin-left: 10px;
}
.inventory-button {
  display: inline-block;
  padding: 5px 10px;
  border: 1px solid #2ec16e;
  border-radius: 4px;
  color: #2ec16e;
  background-color: rgba(41, 172, 63, 0.3);
  margin-bottom: 10px;
}
.outentory-button {
  display: inline-block;
  padding: 5px 10px;
  border: 1px solid #f2bf24;
  border-radius: 4px;
  color: #f2bf24;
  background-color: rgba(231, 187, 42, 0.3);
  margin-bottom: 10px;
  margin-left: 200px;
}
.el-icon-document, .el-icon-goods, .el-icon-money, .el-icon-truck, .el-icon-sold-out, .el-icon-tickets {
  margin-left: 10px;
  color: #409eff;
}
/* 饼图 */
.echart-container {
  width: 600px;
  height: 300px;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  margin-left: -70px;
}
/* 待办事项 */
.task-card {
  width: 370px;
  height: 700px;
  margin: 20px;
  float: right;
  margin-top: -727px;
  padding: 20px;
}
.sx {
  font-weight: bold;
}
/* 入库统计 */
.inventory-stats {
  width: 1250px;
  margin-bottom: 20px;
}
.chart {
  width: 100%;
  height: 400px;
}
.storeClass{
  margin-left: 1050px;
}
.store{
  font-weight: bold;
}
/* 预警信息 */
.warning-card {
  width: 370px;
  margin: 20px;
  float: right;
  height: 350px;
  margin-top: -1030px;
}
.warning-icon {
  font-size: 50px;
  text-align: center;
  padding:10px;
}
.icon-high {
  color: green;
}
.icon-low {
  color: red;
}
.icon-expiry {
  color: orange;
}
.icon-due {
  color: red;
}
.warning-count {
  font-size: 24px;
  font-weight: bold;
}
/* 系统消息 */
.messages-card {
  width: 370px;
  margin: 20px;
  height: 600px;
  float: right;
  margin-top: -620px;
  overflow-y: auto; /* 超出部分滚动 */
}

.el-timeline {
  padding: 10px;
}

.el-timeline-item {
  margin-bottom: 10px;
}

/* 根据内容长度调整样式 */
.el-timeline-item.long-content {
  font-size: 14px; /* 更小的字体 */
}

.el-timeline-item.short-content {
  font-size: 16px; /* 更大的字体 */
}
/* 入库排名 */
.ranking-card {
  width: 800px;
  /* margin: 20px; */
}
.rank-first {
  color: #409EFF; /* Element UI 主题色 */
  font-weight: bold;
}
/* 出库排名 */
.ranking-card-ck {
  width: 800px;
  float: right;
  margin-top: -376px;
  margin-right: 20px;
}
.rank-first-ck {
  color: #f4e644; /* Element UI 主题色 */
  font-weight: bold;
}
</style>
